package com.cloudcc.mobile.db;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;

import com.cloudcc.mobile.entity.IMMessage;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.DbException;

public class IMMessageDB {
	private Context context;
	private DbUtils db;
	public IMMessageDB(Context context,String dbName){
		db=DbUtils.create(context, dbName);
		this.context=context;
	}
	/**
	 * 保存数据库
	 * @param cls
	 * @throws DbException
	 */
	public  void saveIMMessage(IMMessage entity) throws DbException{
		db.save(entity);
	}

	/**
	 * 删除所有消息
	 * @param <T>
	 * @throws DbException 
	 */
	public  void deleteIMMessageAll() throws DbException{
		db.deleteAll(IMMessage.class);
	}
	/**
	 * 删除某个id的消息
	 * @param <T>
	 * @throws DbException 
	 */
	public  void deleteById(long id) throws DbException{
		db.deleteById(IMMessage.class, id);
	}
	/**
	 * 获取系统新消息数量
	 * @param <T>
	 * @throws DbException 
	 */

	public  long getNewIMMessageNum(String keyId) throws DbException{
		if(isExit()){
			long num=db.count(Selector.from(IMMessage.class).where("isNew","=","1").and("messageId","=",keyId));
			return num;
		}else{
			return 0;
		}
	}
	/**
	 * 取最后的消息
	 * @return
	 * @throws DbException
	 */
	public  IMMessage getLastIMMessage(String keyId ) throws DbException{
		if(isExit()){
			List<IMMessage> list=db.findAll(Selector.from(IMMessage.class).where("messageId","=",keyId));
			return list.get(list.size()-1);
		}else{
			return null;
		}

	}
	/**
	 * 查询所有的消息
	 * @return
	 * @throws DbException
	 */
	public List<IMMessage> getList(String keyId) throws DbException{
		List<IMMessage> list=db.findAll(Selector.from(IMMessage.class).where("messageId","=",keyId));
		return list;
	}
	/**
	 * 
	 * @param page 第几页
	 * @param pageNum 一页多少个
	 * @return
	 * @throws DbException
	 */
	public List<IMMessage> getPageList(int offNum,int pageNum,String keyId) throws DbException{
		List<IMMessage> list=new ArrayList<IMMessage>();
		if(isExit()){
			list=db.findAll(Selector.from(IMMessage.class)
					.where("messageId","=",keyId)
					.limit(pageNum)
					.offset(offNum)
					.orderBy("id",true));
		}
		return list;
		
	}
	/**
	 * 判别是否存在
	 * @return
	 * @throws DbException
	 */
	public boolean isExit() throws DbException{
		boolean istable= db.tableIsExist(IMMessage.class);
		if(istable){
			long a=db.count(IMMessage.class);
			if(a>0){
				return true;
			}else{
				return false;
			}
		}
		return false;
	}
}
